package com.itasura.guava.Concurrency.mointor;

import com.itasura.guava.bean.City;
import lombok.extern.slf4j.Slf4j;

/**
 * synchronized 版
 *
 * @author sailor wang
 * @date 2018/10/30 11:17 AM
 * @description
 */
@Slf4j
public class SafeBoxV1<V> {
    private V value;

    public synchronized V get() throws InterruptedException {
        while (value == null) {
            wait();
        }
        V result = value;
        value = null;
        notifyAll();
        return result;
    }

    public synchronized void set(V newValue) throws InterruptedException {
        if (value != null) {
            wait();
        }
        value = newValue;
        notifyAll();
    }

    public static void main(String[] args) throws InterruptedException {


        SafeBoxV1<City> safeBox = new SafeBoxV1<City>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("开始获取值......");
                    City c = safeBox.get();
                    log.info("获取完成，值 -> {}", c);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Thread.sleep(5000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    City city = new City();
                    city.setName("上海");
                    log.info("开始设置值......");
                    safeBox.set(city);
                    log.info("设置完成......");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}